package com.changgou.file.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.changgou.file.service.FileService;
import com.changgou.framework.entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Yang
 * @date 2020/11/6
 */
@Service
public class FileServiceImpl implements FileService {
    @Value("${alibaba.endpoint}")
    private String endpoint;
    @Value("${alibaba.AccessKeyID}")
    private String accessKeyId;
    @Value("${alibaba.AccessKeySecret}")
    private String accessKeySecret;
    @Value("${alibaba.bucketName}")
    private String bucketName;
    //返回地址的前缀
    @Value("${alibaba.prefix}")
    private String prefix;

    @Override
    public Result uploadFile(MultipartFile file) {
        //处理得到2020/11/06/fjdkjfdkj.jpg的文件名,返回的地址上加上bucket即可访问到
        String originalName = file.getOriginalFilename();
        String end = originalName.substring(originalName.lastIndexOf(".") + 1, originalName.length());
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String format1 = format.format(new Date());
        String newName = format1 + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + end;
        OSS ossClient = null;
        InputStream inputStream = null;
        String tag = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // meta设置请求头
            ObjectMetadata meta = new ObjectMetadata();
            String contentType = "image/" + end;
            meta.setContentType(contentType);
            inputStream = file.getInputStream();
            ossClient.putObject(bucketName, newName, inputStream, meta);

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        } finally {

            ossClient.shutdown();
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return Result.ok(prefix+newName);
    }
}
